﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ReflectionDemo
{
    public class ModelBase<T>
    {
        List<T> list = new List<T>();

        //添加项
        public void Add(T t)
        {
            list.Add(t);
        }
        //获取对象列表
        public List<T> GetList()
        {
            return list;
        }

        //生成信息字符串
        public string GetInfo(T t)
        {
            string str = "";
            Type type = typeof(T);
            var props = type.GetProperties();//获取公共属性数组
            foreach (var p in props)
            {
                if (str != "")
                    str += ", ";
                str += p.GetValue(t) ?? "";
            }
            return str;
        }

        /// <summary>
        /// 找到指定id的对象
        /// </summary>
        /// <param name="id"></param>
        /// <param name="idName">编号属性名</param>
        /// <returns></returns>
        public T Find(int id, string idName)
        {
            Type type = typeof(T);
            PropertyInfo pId = type.GetProperty(idName);
            if (pId != null)
            {
                foreach (T t in list)
                {
                    if ((int)pId.GetValue(t) == id)
                        return t;
                }
            }
            return default;
        }
    }
}
